﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneAppCheckSensors
{
    using Microsoft.Live;
    using Microsoft.Live.Controls;

    public partial class PageSaveToSkyDrive : PhoneApplicationPage
    {
        public PageSaveToSkyDrive()
        {
            InitializeComponent();
        }

        private bool fromSensorPage = true;
        string fileUrl;
        string sensorType;
        private string folderInSkyDrive = "folder-in-skydrive";
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (App.LiveSession == null)
            {
                SigninPanel.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                SigninPanel.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (fromSensorPage)
            {
                var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                if (!appSettings.Contains(folderInSkyDrive))
                {
                    appSettings.Add(folderInSkyDrive, "");
                }
                 tbFolder.Text = appSettings[folderInSkyDrive] as string;

                if (NavigationContext.QueryString.TryGetValue("datafile", out fileUrl))
                {
                    try
                    {
                        var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                        using (var stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileUrl, System.IO.FileMode.Open, storage))
                        {
                            var reader = new System.IO.StreamReader(stream);
                            tbContent.Text = reader.ReadToEnd();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed to get sensor data! : " + ex.Message);
                    }
                }
                NavigationContext.QueryString.TryGetValue("sensortype", out sensorType);
                if ((!string.IsNullOrWhiteSpace(tbFolder.Text)) && (!string.IsNullOrWhiteSpace(tbContent.Text)))
                {
                    buttonSave.IsEnabled = true;
                }
            }
            else
            {
                fromSensorPage = true;
            }

            base.OnNavigatedTo(e);
        }
        private void buttonSignin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
            {
                App.LiveSession = e.Session;
                SigninPanel.Visibility = System.Windows.Visibility.Collapsed;
                UploadPanel.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                MessageBox.Show("Signin Failed. ");
            }
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbFolder.Text))
                {
                    var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                    appSettings[folderInSkyDrive] = tbFolder.Text.Trim();
                }
                LiveConnectClient client = new LiveConnectClient(App.LiveSession);
                var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
#if false
                using (var fstream = storage.OpenFile(fileUrl, System.IO.FileMode.Open))
                {
                    string fileName = sensorType + DateTime.Now.ToString("yyyymmdd_hhMMss") + ".xml";
                    client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
                    client.UploadAsync(tbFolder.Text, fileName, fstream);
                }
#endif
                client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
                client.GetAsync("me/skydrive/files?filter=folders", client);
           //     storage.DeleteFile(fileUrl);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to upload file. : " + ex.Message);
            }
        }

        void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    string path = null;
                    Dictionary<string, object> folderData = e.Result as Dictionary<string, object>;
                    List<object> folders = (List<object>)folderData["data"];
                    foreach (var item in folders)
                    {
                        Dictionary<string, object> folder = item as Dictionary<string, object>;
                        if (folder["name"].ToString() == tbFolder.Text.Trim())
                        {
                            path = folder["id"].ToString();
                            break;
                        }
                    }
                    if (path != null)
                    {
                        UploadFile(path, e.UserState as LiveConnectClient);
                    }
                    else
                    {
                        Dictionary<string, object> newFolder = new Dictionary<string, object>();
                        newFolder.Add(tbFolder.Text.Trim(), newFolder);
                        var client = e.UserState as LiveConnectClient;
                        client.PostCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_CreateFolderCompleted);
                        client.PostAsync("me/skydrive", newFolder, client);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
#if false
            if (!string.IsNullOrWhiteSpace(tbFolder.Text))
            {
                var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                appSettings[folderInSkyDrive] = tbFolder.Text.Trim();
            }
            string path = null;
            foreach (var key in e.Result.Keys)
            {
                var r = e.Result[key];
                if (r is List<object>)
                {
                    var l = r as List<object>;
                    foreach (var d in l)
                    {
                        if (d is Dictionary<string, object>)
                        {
                            var s = d as Dictionary<string, object>;
                            if (s.ContainsKey("type") && s.ContainsKey("name") && s.ContainsKey("id"))
                            {
                                if (s["type"].ToString().CompareTo("folder") == 0)
                                {
                                    string name = s["name"] as string;
                                    if (name.CompareTo(tbFolder.Text.Trim()) == 0)
                                    {
                                        path = s["id"] as string;
                                        if (s.ContainsKey("path"))
                                        {
                                        }
                                      //  path = s["link"] as string;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (path != null)
                    {
                        break;
                    }
                }

            }

            if (path != null)
            {
                var client = e.UserState as LiveConnectClient;
                var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
//                using (var fstream = storage.OpenFile(fileUrl, System.IO.FileMode.Open))
                {
                    fstream = storage.OpenFile(fileUrl, System.IO.FileMode.Open);
                    string fileName = sensorType + DateTime.Now.ToString("yyyymmdd_hhMMss") + ".xml";
                    client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
             //       path = "me/skydrive/files/" + tbFolder.Text.Trim();
                    client.UploadAsync(path, fileName, fstream);
                }
            }
#endif
            }

        void client_CreateFolderCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Dictionary<string, object> folder = e.Result as Dictionary<string, object>;
                string path = folder["id"].ToString();
                var client = e.UserState as LiveConnectClient;
                UploadFile(path, client);
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void UploadFile(string path, LiveConnectClient client)
        {
            var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            {
                fstream = storage.OpenFile(fileUrl, System.IO.FileMode.Open);
                client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
                client.UploadAsync(path, fileUrl+".txt", fstream);
            }
        }

        private System.IO.IsolatedStorage.IsolatedStorageFileStream fstream;

        void client_UploadCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result != null)
                {
                    try
                    {
                        if (e.Result.Keys.Contains("id"))
                        {
                            foreach (var rkey in e.Result.Keys)
                            {
                                object rval = e.Result[rkey];
                                MessageBox.Show("Done.");
                                var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                                fstream.Close();
                                fstream.Dispose();
                                storage.DeleteFile(fileUrl);
                                buttonSave.IsEnabled = false;
                                NavigationService.GoBack();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }
    }
}